<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { validateUser } from '../services/UserService'
import { createStarfield, showTemporaryMessage } from '../utils/uiUtils'
import { setStorage, getStorage, removeStorage } from '../utils/storage'

const router = useRouter()
const username = ref('')
const password = ref('')
const error = ref('')
const isLoading = ref(false)

// 验证用户名格式
const validateUsername = (username) => {
  // 用户名至少3个字符，不超过20个字符
  if (username.length < 3 || username.length > 20) {
    return '用户名长度必须在3-20个字符之间'
  }
  // 用户名只能包含字母、数字和下划线
  if (!/^[a-zA-Z0-9_]+$/.test(username)) {
    return '用户名只能包含字母、数字和下划线'
  }
  return ''
}

// 验证密码格式
const validatePassword = (password) => {
  // 密码至少6个字符
  if (password.length < 6) {
    return '密码长度至少为6个字符'
  }
  // 密码强度检查（可选）
  const hasLetter = /[a-zA-Z]/.test(password)
  const hasNumber = /[0-9]/.test(password)
  // 不强制要求复杂密码，但提供提示
  if (!hasLetter || !hasNumber) {
    // 这里不返回错误，只是在UI上可以显示提示
    return ''
  }
  return ''
}

// 处理登录提交
const handleLogin = async (e) => {
  e.preventDefault()
  
  // 表单验证
  if (!username.value || !password.value) {
    error.value = '请输入用户名和密码'
    return
  }
  
  // 验证用户名格式
  const usernameError = validateUsername(username.value)
  if (usernameError) {
    error.value = usernameError
    return
  }
  
  // 验证密码格式
  const passwordError = validatePassword(password.value)
  if (passwordError) {
    error.value = passwordError
    return
  }
  
  isLoading.value = true
  error.value = ''
  
  try {
    // 验证用户凭证（使用加密后的密码验证）
    const isValidUser = validateUser(username.value, password.value)
    
    if (isValidUser) {
      // 保存用户登录状态
      setStorage('username', username.value)
      setStorage('isLoggedIn', 'true')
      
      // 显示成功消息
      showTemporaryMessage('登录成功，正在跳转...', (msg) => {
        error.value = msg
      })
      
      // 延迟跳转，让用户看到成功消息
      setTimeout(() => {
        // 检查是否有重定向URL
        const redirectUrl = getStorage('redirectAfterLogin')
        if (redirectUrl) {
          removeStorage('redirectAfterLogin')
          router.push(redirectUrl)
        } else {
          // 默认跳转到游戏页面
          router.push('/games')
        }
      }, 1000)
    } else {
      error.value = '用户名或密码错误'
    }
  } catch (err) {
    console.error('登录失败:', err)
    error.value = '登录失败，请稍后重试'
  } finally {
    isLoading.value = false
  }
}

// 跳转到注册页面
const goToRegister = () => {
  router.push('/register')
}

// 跳转到忘记密码页面
const goToForgotPassword = () => {
  router.push('/forgot-password')
}

// 组件挂载和卸载处理
let cleanupMeteors = null

onMounted(() => {
  // 使用工具函数创建星空背景
  cleanupMeteors = createStarfield('star-background')
})

onUnmounted(() => {
  if (cleanupMeteors) {
    cleanupMeteors()
  }
})
</script>

<template>
  <div class="login-container">
    <!-- 星空背景组件 -->
    <div class="star-background">
      <div class="gradient-animation"></div>
    </div>
    
    <div class="login-form">
      <h2 class="login-title">用户登录</h2>
      <form @submit="handleLogin">
        <div class="form-group">
          <label for="username">用户名</label>
          <input
            id="username"
            type="text"
            v-model="username"
            placeholder="请输入用户名"
            class="form-input"
          />
        </div>
        <div class="form-group">
          <label for="password">密码</label>
          <input
            id="password"
            type="password"
            v-model="password"
            placeholder="请输入密码"
            class="form-input"
          />
        </div>
        <div v-if="error" class="error-message">{{ error }}</div>
        <button type="submit" class="login-button">登录</button>
      </form>
      <div class="additional-links">
        <div class="register-link">
          还没有账号？<button @click="goToRegister" class="link-button">立即注册</button>
        </div>
        <div class="forgot-password-link">
          <button @click="goToForgotPassword" class="link-button">忘记密码？</button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  margin: 0;
  padding: 0;
}

.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  width: 100vw;
  position: fixed;
  top: 0;
  left: 0;
}

/* 确保背景在底层 */
.star-background {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, var(--vt-c-gradient-1) 0%, var(--vt-c-gradient-2) 50%, var(--vt-c-gradient-3) 100%);
  z-index: -1;
  overflow: hidden;
}

/* 星空背景样式 - 星星 */
.star {
  position: absolute;
  background-color: white;
  border-radius: 50%;
  animation: twinkle 2s infinite alternate;
}

@keyframes twinkle {
  0% {
    opacity: 0.2;
  }
  100% {
    opacity: 1;
  }
}

/* 星空背景样式 - 流星 */
.meteor {
  position: absolute;
  height: 2px;
  background: linear-gradient(90deg, transparent, white, transparent);
  animation: meteor 2s linear forwards;
  pointer-events: none;
}

@keyframes meteor {
  0% {
    transform: rotate(45deg) translateX(-100%);
    opacity: 0;
  }
  10% {
    opacity: 0.8;
  }
  90% {
    opacity: 0.8;
  }
  100% {
    transform: rotate(45deg) translateX(100vw);
    opacity: 0;
  }
}

.login-form {
  background-color: rgba(255, 255, 255, 0.1);
  padding: 3rem;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(102, 126, 234, 0.2);
  width: 90%;
  max-width: 500px;
  min-height: 60vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  backdrop-filter: blur(5px);
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.login-title {
  text-align: center;
  margin-bottom: 2rem;
  color: rgba(255, 255, 255, 0.8);
  font-size: 1.8rem;
  text-shadow: 0 0 10px rgba(102, 126, 234, 0.5), 0 0 20px rgba(118, 75, 162, 0.4);
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.9), rgba(255, 255, 255, 0.6));
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.form-group {
  margin-bottom: 1.5rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 500;
  color: rgba(255, 255, 255, 0.7);
  font-size: 1rem;
  text-shadow: 0 0 5px rgba(102, 126, 234, 0.3);
}

.form-input {
  width: 100%;
  padding: 1rem;
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 6px;
  font-size: 1.1rem;
  transition: all 0.3s ease;
  background-color: rgba(255, 255, 255, 0.05);
  color: rgba(255, 255, 255, 0.9);
  text-shadow: 0 0 5px rgba(102, 126, 234, 0.3);
}

.form-input::placeholder {
  color: rgba(255, 255, 255, 0.5);
}

.form-input:focus {
  outline: none;
  border-color: #42b983;
  box-shadow: 0 0 0 3px rgba(66, 185, 131, 0.3);
  background-color: rgba(255, 255, 255, 0.1);
}

.error-message {
  color: rgba(255, 77, 79, 0.9);
  margin-bottom: 1rem;
  font-size: 0.9rem;
  text-align: center;
  padding: 0.5rem;
  background-color: rgba(255, 77, 79, 0.1);
  border-radius: 4px;
  text-shadow: 0 0 5px rgba(255, 77, 79, 0.3);
}

.login-button {
  width: 100%;
  padding: 1rem;
  background-color: rgba(66, 185, 131, 0.2);
  color: rgba(255, 255, 255, 0.9);
  border: 1px solid rgba(66, 185, 131, 0.4);
  border-radius: 6px;
  font-size: 1.1rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-bottom: 1.5rem;
  text-shadow: 0 0 5px rgba(66, 185, 131, 0.5);
}

.login-button:disabled {
  background-color: #666;
  cursor: not-allowed;
  opacity: 0.7;
  transform: none;
}

/* 加载动画 */
@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.login-button .loading {
  display: inline-block;
  width: 16px;
  height: 16px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  border-top-color: white;
  animation: spin 0.8s ease-in-out infinite;
  margin-right: 8px;
  vertical-align: middle;
}

.additional-links {
  text-align: center;
  margin-top: auto;
}

.register-link,
.forgot-password-link {
  margin-bottom: 0.8rem;
  color: rgba(255, 255, 255, 0.6);
  font-size: 1rem;
  text-shadow: 0 0 5px rgba(102, 126, 234, 0.3);
}

.link-button {
  background: none;
  border: none;
  color: rgba(66, 185, 131, 0.8);
  cursor: pointer;
  font-size: inherit;
  padding: 0;
  text-decoration: underline;
  font-weight: 500;
  text-shadow: 0 0 5px rgba(66, 185, 131, 0.3);
}

.link-button:hover {
  color: rgba(66, 185, 131, 1);
  text-shadow: 0 0 8px rgba(66, 185, 131, 0.5);
}

.login-button:hover:not(:disabled) {
  background-color: rgba(66, 185, 131, 0.3);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(66, 185, 131, 0.4);
  border-color: rgba(66, 185, 131, 0.6);
  text-shadow: 0 0 8px rgba(66, 185, 131, 0.7);
}
</style>